import router from '@/router'
import store from '@/store'
import Nprogress from 'nprogress'
import { asyncRoutes } from '@/router'
import 'nprogress/nprogress.css'

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // 开启进度条
  Nprogress.start()
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      // 如果不是next() 则手动关闭进度条
      next('/')
      Nprogress.done()
    } else {
      if (!store.getters.userId) {
        const userInfo = await store.dispatch('user/getUserInfo')
        // 拿到用户的权限点
        const userPerms = userInfo.roles.menus
        // 和动态路由做对比
        const userRoutes = asyncRoutes.filter(item => userPerms.includes(item.name))
        // 将动态路由添加到vuex中 用于菜单显示
        store.commit('user/setRoutes', userRoutes)
        // 添加动态路由到静态路由后面 由于之前404页面是放在静态页面最后的 现在加上动态路由就会把404夹在中间 所以这里手动将404放在最后面
        router.addRoutes([...userRoutes, { path: '*', redirect: '/404', hidden: true }])
        // 必须添加下面这行代码next(to.path) 不然刷新页面走next()会获取不到路由信息 这里router添加动态路由之后需要转发一下 router的已知缺陷
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      Nprogress.done()
    }
  }
})

router.afterEach((to, from, next) => {
  // 关闭进度条
  Nprogress.done()
})
